<template>
  <el-dialog
    :visible.sync="dialogVisible"
    @close="handleClose"
    width="80%"
    :title="dialogTitle"
    v-loading="loading"
  >
    <!-- 对话框内容 -->
    <div v-if="data.length">
      <el-table
        :data="tableData"
        border
        v-if="type != 'comment'"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>

        <el-table-column
          v-for="key in tableFields"
          :key="key"
          :label="formatLabel(key)"
        >
          <template slot-scope="scope" v-if="key !== 'id'">
            <span v-if="key === 'create_time' || key === 'update_time'">
              {{ scope.row[key] | formatDate }}
            </span>
            <span v-else>{{ scope.row[key] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- <el-button
              size="mini"
              @click="handleRecover(scope.$index, scope.row)"
              >恢复</el-button
            > -->
            <!-- <el-button size="mini"
                     type="info"
                     @click="handleEdit(scope.$index, scope.row)">更改密码</el-button> -->
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-table
        :data="tableData"
        border
        v-else-if="type == 'comment'"
        :default-expand-all="false"
        row-key="id"
        @expand-change="handleNodeExpand"
        :tree-props="{ children: 'children' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column type="expand">
          <template
            slot-scope="props"
            style="display:flex;justify-content:center"
          >
            <el-table
              :data="props.row.children.payload"
              v-if="props.row.children.payload"
              @selection-change="ReplyCommentSelectionChange"
              style="width: 100%"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column prop="commenter_name" label="时间" width="100">
                <template slot-scope="scope">
                  <span>{{ scope.row.create_time | formatDate }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="commenter_name" label="评论人" width="100">
              </el-table-column>
              <el-table-column
                prop="to_commenter_name"
                label="被评论人"
                width="100"
              >
              </el-table-column>
              <el-table-column
                prop="comment_content"
                label="评论内容"
                width="100"
              >
              </el-table-column>
              <el-table-column prop="like_count" label="点赞数" width="100">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    @click="DeleteReplyComment(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <div v-else class="empty-container">
              <img
                src="@/assets/img/comment-empty.png"
                style="width:300px;margin:0 auto;"
              />
            </div>
            <el-pagination
              small
              :page-size="props.row.children.limit"
              @current-change="ReplyPageChange(props.row.children)"
              layout="prev, pager, next"
              :total="props.row.children.count"
            >
            </el-pagination>
          </template>
        </el-table-column>
        <el-table-column
          v-for="key in tableFields"
          :key="key"
          :label="formatLabel(key)"
        >
          <template slot-scope="scope" v-if="key !== 'id'">
            <span v-if="key === 'create_time' || key === 'update_time'">
              {{ scope.row[key] | formatDate }}
            </span>
            <span v-else>{{ scope.row[key] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- <el-button
              size="mini"
              @click="handleRecover(scope.$index, scope.row)"
              >恢复</el-button
            > -->
            <!-- <el-button size="mini"
                     type="info"
                     @click="handleEdit(scope.$index, scope.row)">更改密码</el-button> -->
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="count"
        layout="prev, pager, next"
        class="pagination"
      ></el-pagination>
    </div>
    <div v-else>
      <img src="@/assets/img/search-empty.png" alt="" />
    </div>
    <el-button
      v-if="data.length > 0"
      type="danger"
      @click="OriginateBatchDelete"
      style="margin:10px"
      >批量删除</el-button
    >
    <el-button
      v-if="data.length > 0 && type == 'comment'"
      type="danger"
      @click="OriginateBatchDeleteReply"
      style="margin:10px"
      >批量删除回复评论</el-button
    >
  </el-dialog>
</template>

<script>
import {
  OriginateDelete,
  OriginateBatchDelete
} from '@/utils/request/originate.js'
export default {
  props: {
    data: {
      type: Array,
      required: true
    },
    dialogTitle: {
      type: String,
      default: '编辑'
    },
    visible: {
      type: Boolean,
      required: true
    },
    pageSize: {
      type: Number,
      required: true
    },
    total: {
      type: Number,
      required: true
    },
    type: {
      type: String,
      required: true
    },
    commentType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      tableFields: [],
      currentPage: 1,
      pageSizes: [10, 20, 30, 50],
      count: 0,
      selectedItems: [],
      tableData: [],
      loading: false,
      currentComment: null,
      selectedReply: []
    }
  },
  computed: {},
  watch: {
    // 替换数据
    data: {
      immediate: true,
      handler(newValue) {
        if (Array.isArray(newValue) && newValue.length) {
          this.tableFields = Object.keys(newValue[0])
        }
        // 重新获取表格数据
        this.getTableData()
      }
    },
    visible: {
      immediate: true,
      handler(val) {
        this.dialogVisible = val
      }
    },
    pageSize: {
      immediate: true,
      handler(val) {
        this.pageSize = val
      }
    },
    total: {
      immediate: true,
      handler(val) {
        this.count = val
      }
    }
  },
  methods: {
    ReplyCommentSelectionChange(s) {
      this.selectedReply = s
    },
    // 展开回复评论列表
    async handleNodeExpand(node) {
      // 初始化数据
      this.$set(node, 'children', {})
      this.$set(node.children, 'limit', 10)
      this.$set(node.children, 'page', 1)
      const res = await this.$API.comment.getReplyCommentDeleteList(
        node.id,
        node.children.limit,
        node.children.page
      )
      console.log('reply', res)
      // 如果未获取到数据就退回一页重新获取数据
      if (res && !res.data) {
        if (node.children && node.children.page <= 1) {
          return this.$set(node, 'children', [])
        } else {
          this.$set(node.children, 'page', node.children.page--)
          this.handleNodeExpand(node)
        }
      }
      if (res.status === 200) {
        this.$set(node, 'children', {
          count: res.data.count,
          page: node.page,
          payload: res.data.payload
        })
        this.currentComment = node
      }
    },
    // 多选项切换时
    handleSelectionChange(selection) {
      this.selectedItems = selection
    },
    handleConfirm() {
      // 自定义确定按钮的事件逻辑
      // 在此处编写您希望在确定按钮上触发的逻辑代码
      // 可以根据需要传递参数或调用其他方法
      // 示例：触发一个自定义事件，并传递表单数据对象
      this.$emit('custom-confirm', this.data)

      // 关闭对话框
      this.dialogVisible = false
    },
    handleClose() {
      // 取消按钮的事件逻辑
      // 在此处编写取消按钮的逻辑代码
      // 示例：关闭对话框
      this.dialogVisible = false
      this.$emit('custom-close')
    },
    // 根源删除
    handleDelete(index, item) {
      const { type, commentType } = this
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          // 根据类型删除
          OriginateDelete(type, item, commentType)
            .then(() => {
              // 刷新列表
              this.$emit('custom-reload')
              this.loading = false
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            })
            .catch(err => {
              this.loading = false
              console.log(err)
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    DeleteReplyComment(index, item) {
      const { type } = this
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          // 根据类型删除
          OriginateDelete('reply', item)
            .then(() => {
              // 刷新列表
              this.handleNodeExpand(this.currentComment).then(() => {
                this.loading = false

                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
              })
            })
            .catch(err => {
              this.loading = false
              console.log(err)
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 批量删除
    OriginateBatchDelete() {
      const { type } = this

      if (this.selectedItems.length == 0)
        return this.$message.warning('请选择删除的数据')
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          // 获取选中的id
          let ids = this.selectedItems.map(item => item.id)
          // 根据类型删除
          OriginateBatchDelete(type, ids, this.selectedItems, this.commentType)
            .then(() => {
              // 刷新列表
              this.$emit('custom-reload')
              this.loading = false
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            })
            .catch(err => {
              console.log(err)
              this.loading = false
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 批量删除回复
    OriginateBatchDeleteReply() {
      if (this.selectedReply.length == 0)
        return this.$message.warning('请选择删除的数据')
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          // 获取选中的id
          let ids = this.selectedReply.map(item => item.id)
          // 根据类型删除
          OriginateBatchDelete('reply', ids)
            .then(() => {
              // 刷新列表
              // 刷新列表
              this.handleNodeExpand(this.currentComment).then(() => {
                this.loading = false

                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
              })
              this.loading = false
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            })
            .catch(err => {
              console.log(err)
              this.loading = false
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 美化label
    formatLabel(key) {
      // 根据需要进行label的格式化，这里可以添加逻辑来美化label的显示
      // 例如，将key转换为首字母大写的形式
      const formattedLabel = key.charAt(0).toUpperCase() + key.slice(1)
      return formattedLabel
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.currentPage = 1
      this.$emit('page-size-change', pageSize) // 触发自定义事件，传递页数改变的信息给父组件
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.$emit('current-page-change', currentPage) // 触发自定义事件，传递页数改变的信息给父组件
    },
    // 处理表格数据
    getTableData() {
      if (!this.data || !this.tableFields.length) {
        return (this.tableData = [])
      }

      this.tableData = this.data.map(item => {
        const rowData = {}
        this.tableFields.forEach(key => {
          rowData[key] = item[key]
        })
        return rowData
      })
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
